package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock {

    private static final String ID_PREFIX = cn.hutool.core.lang.UUID.
            randomUUID().toString(true) + "-";

    private final StringRedisTemplate stringRedisTemplate;
    private final String key;

    public SimpleRedisLock( String key, StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.key = key;
    }

    @Override
    public boolean tryLock(long timeoutSec) {

        //获取线程标识
        String id = ID_PREFIX + Thread.currentThread().getId();
        //获取锁
        Boolean b = stringRedisTemplate.opsForValue().setIfAbsent(
                key,
                id,
                timeoutSec,
                TimeUnit.SECONDS);
        return Boolean.TRUE.equals(b);
    }

    @Override
    public void unlock() {
        //获取线程标识
        String id = ID_PREFIX + Thread.currentThread().getId();

        //获取锁中的标识
        String lockId = stringRedisTemplate.opsForValue().get(key);

        //判断是否是自己的锁
        if (id.equals(lockId)) {
            //释放锁
            stringRedisTemplate.delete(key);
        }

    }
}
